package com.EJ.ejcompanyweb.updata;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.nfc.Tag;
import android.util.Log;

import com.EJ.ejcompanyweb.MainActivity;
import com.EJ.ejcompanyweb.R;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import constacne.UiType;
import listener.UpdateDownloadListener;
import model.UiConfig;
import model.UpdateConfig;
import update.UpdateAppUtils;

public class UpdataThread extends Thread {
    private Context context;
    private String TAG=this.getClass().getSimpleName();
    private  UpdataMessage message=null;
    private String UpdataUrl;
    private UpdataThread(Context context,String UpdataUrl) {
        this.context = context;
        this.UpdataUrl=UpdataUrl;
    }

    @Override
    public void run() {
        super.run();
        try {
                StartUpdata(UpdataUrl);
        }catch (Exception e){
            //配置更新出错
            Log.e(TAG,"访问更新服务器失败");
        }
        if (message!=null) {
            //在主线程上执行更新操作
            MainActivity.MAINACTIVITY_HANDLER.post(new Runnable() {
                @Override
                public void run() {
                    onPostExecute(message);
                }
            });
        }

    }

    private UpdataMessage StartUpdata (String params) {
        try{
            //1.将url网络地址字符串封装成url对象
            URL url=new URL(params);
            //2.打开url对象的网络链接  获取网络链接对象
            HttpURLConnection conn= (HttpURLConnection) url.openConnection();
            //3.进行网络链接的设置
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            //4.获取响应状态码
            /**
             200(正常),206请求部分数据
             302/307(临时重定向),
             304(未修改),
             404(找不到),
             500(服务器内部错误)
             */
            int responseCode=conn.getResponseCode();
            //5.判断状态码  如果为200说明成功则进行读取操作
            if(responseCode==200){
                //开始读取网络输入流
                InputStream inputStream=conn.getInputStream();
                message =new PullParserHelper().startParser(inputStream);
            }
            conn.disconnect();//关掉连接
        }catch (Exception e){
            e.printStackTrace();
        }
        //返回字节数组
        return message;
    }

    /**
     * 需要在主线程中执行
      * @param updataMessage
     */
    public void onPostExecute(UpdataMessage updataMessage) {
        if (updataMessage==null){
            return;
        }
        Log.e(TAG,updataMessage.toString());
        if (updataMessage!=null&&updataMessage.getServerVersionCode()>getVersionCode()){
            UpdateConfig updateConfig = new UpdateConfig();
            updateConfig.setCheckWifi(true);
            updateConfig.setNeedCheckMd5(false);
            updateConfig.setShowNotification(true);
            updateConfig.setNotifyImgRes(R.drawable.ic_update_logo);
            //服务器上apk版本名
            updateConfig.setServerVersionName(updataMessage.getServerVersionName());
            //是否强制更新，强制时无取消按钮
            updateConfig.setForce(true);
            // updateConfig.setApkSavePath(Environment.getExternalStorageDirectory().getAbsolutePath() +"/teprinciple");
            // Log.e(TAG,updateConfig.getApkSavePath());
            UiConfig uiConfig = new UiConfig();
            uiConfig.setUiType(UiType.PLENTIFUL);
            UpdateAppUtils
                    .getInstance()
                    .apkUrl(updataMessage.getApkUrl())
                    .updateTitle(updataMessage.getUpdateTitle())
                    .updateContent(updataMessage.getUpdateContent())
                    .uiConfig(uiConfig)
                    .updateConfig(updateConfig)
                    .setUpdateDownloadListener(new UpdateDownloadListener() {
                        @Override
                        public void onStart() {
                        }
                        @Override
                        public void onDownload(int i) {
                            Log.e(TAG,"下载进度"+i);
                        }
                        @Override
                        public void onFinish() {
                        }
                        @Override
                        public void onError(Throwable throwable) {
                        }
                    })
                    .update();
        }else {
            Log.d(TAG,"暂时不需要更新");
        }
    }
    private  int getVersionCode(){
        try {
            PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(),0);
            Log.e(TAG,pi.versionCode+"");
            return pi.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public void onDestroy() {
        if (context!=null){
            context=null;
        }
        if (message!=null){
            message=null;
        }
        if (UpdataUrl!=null){
            UpdataUrl=null;
        }
    }

    private static UpdataThread instance;
    public static UpdataThread getInstance(Context context,String UpdataUrl) {
        if(instance == null)
        {
            synchronized (UpdataThread.class)
            {
                if(instance == null)
                {
                instance = new UpdataThread(context,UpdataUrl);
            }
            }
        }
        return instance;
    }
}
